import csv
from collections import defaultdict

import pandas as pd

lianjie_map = defaultdict(list)


# 生成当前设备连接的设备和端口
def t1(row):
    try:
        zj = jibie.loc[row['Z端设备'], '级别']
        aj = jibie.loc[row['A端设备'], '级别']
    except:
        return
    print(1)
    if (aj - 1 != zj) | (zj == -1):
        return
    if not isinstance(row['A端端口'], str):
        raise TypeError(f"{row['A端端口']},,预期字符串类型，得到 {type(row['A端端口']).__name__}")
    lianjie_map[row['Z端设备']].append(
        [row['Z端设备'] + "|" + row['Z端端口'] + "-->" + row['A端设备'] + "|" + row['A端端口'], row['A端设备']])


def t2(row):
    print(row.name)
    l = [row['Z端设备'] + "|" + row['Z端端口'] + "-->" + row['A端设备'] + "|" + row['A端端口']]
    dfs(row['A端设备'], l)


"""
dev 当前下级设备
line 当前连线

"""


def dfs(dev, line):
    # 判断当前连线是否到达末尾
    if dev not in lianjie_map:
        writer.writerow(line)
        return
    next_port = lianjie_map.get(dev)
    for port in next_port:
        line.append(port[0])
        dfs(port[1], line)
        line.pop()


jibie = pd.read_csv(r"D:\temp\设备级别.csv")
jibie=jibie.set_index("设备")
df = pd.read_csv(r"D:\temp\物理链路的配置查询结果.csv",
                 usecols=["A端设备", "A端端口", "Z端设备", "Z端端口"], dtype=str)
df = df.dropna(subset=['A端设备', 'Z端设备'])
df['A端端口'] = df['A端端口'].astype(str)
df['Z端端口'] = df['Z端端口'].astype(str)
df.apply(t1, axis=1)
first = df[~df['Z端设备'].isin(df['A端设备'])]
# 使用 csv 模块写入文件
with open("/temp/拓扑.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    first.apply(t2, axis=1)
